package com.tc.quartz.support.controller;

import com.tc.quartz.frame.base.BaseController;
import org.quartz.CronExpression;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.sql.Timestamp;
import java.text.ParseException;
import java.util.Date;

/**
 * cron
 * @author yongjin.ye
 *
 */
@RequestMapping(value = "/cron")
@Controller
public class CronController extends BaseController {

	/**
	 * 进入cron页面 
	 */
	@RequestMapping(value="/cron", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
	public String cron() {
		return "forward:/cron.jsp";
	}
	
	/**
	 * 生成时间
	 * @return
	 * @throws ParseException 
	 */
	@RequestMapping(value="/cron", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String cronGen(String CronExpression) throws ParseException {
		try {
			CronExpression cron = new CronExpression(CronExpression);
			StringBuffer sbf = new StringBuffer();
			Date date = new Date();
			for (int i = 0; i < 20; i++) {
				if (null == date) break;
				date = cron.getTimeAfter(date);
				sbf.append(null == date ? "--" : new Timestamp(date.getTime())).append("<br/>");
			}
			return sbf.toString();
		} catch (Exception e) {
			log.error("根据cron生成时间异常", e);
			return "ERROR";
		}
	}
	
}